﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using org.alex.edss.Security;

namespace TestClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private bool handok = false;

        private string filename;

        private long count = 0;

        private long filelength = 0;

        private Socket sock;

        private bool cand;

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists("d:\\"))
            {
                lbPath.Text = "d:\\";
            }
            else
            {
                lbPath.Text = "N/A";
            }
            IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddr = ipHost.AddressList[0];   

            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //sock.ReceiveTimeout = 1000;
            sock.Bind(
                new IPEndPoint(
                    ipAddr, 18000
                                )
                    );
            lbPort.Text = "10898";
            Rs.Text = "Init ok\r\n";
            Rs.SelectionStart = Rs.TextLength;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[16];
            string QQ = "1000000023826299";
            for (int i = 0; i < 16; i++)
            {
                data[i] = byte.Parse(QQ.Substring(i, 1));
            }
            sock.Send(data);
            byte[] rand=new byte[2];
            if (sock.Receive(rand) > 1)
            {
                int r1 = rand[0];
                int r2 = rand[1];
                sock.Send(new byte[1] { (byte)(r1 + r2) });
                byte[] rs = new byte[1];
                rs[0] = 1;
                sock.Receive(rs);
                if (rs[0] == 0)
                {
                    Rs.Text = "Hand Shake Ok\r\n" + Rs.Text;
                    handok = true;
                    button2.Enabled = true;
                }
                else
                {
                    Rs.Text = "Hand Shake False\r\n" + Rs.Text;
                }
            }
            Rs.SelectionStart = Rs.TextLength;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (handok)
            {
                if (handok)
                {
                    if (Cmd.Text.StartsWith("get"))
                    {
                        if (lbPath.Text != "N/A")
                        {
                            SendCommandData();
                        }
                        else
                        {
                            MessageBox.Show("请设定保存下载文件的目录");
                        }
                    }
                    else
                    {
                        SendCommandData();
                    }
                }
            }
            Rs.SelectionStart = Rs.TextLength;
        }

        private void SendCommandData()
        {
            
            bool candown = false;
            byte[] CmdData = Encoding.UTF8.GetBytes(this.Cmd.Text);
            byte[] EncryptoCmd = DES.GetTransfer().Encrypto(CmdData, "12345678");
            MemoryStream ms = new MemoryStream();
            ms.Write(EncryptoCmd, 0, EncryptoCmd.Length);
            ms.WriteByte((byte)13);
            ms.WriteByte((byte)10);
            byte[] data = ms.ToArray();
            sock.Send(data);
            byte[] buffer = new byte[4096];
            int rc = sock.Receive(buffer);
            ms.SetLength(0);
            ms.Write(buffer, 0, rc);

            if (rc > 8)
            {
                candown = false;
                if (Cmd.Text.StartsWith("get"))
                {
                    byte[] DecryptoData = DES.GetTransfer().Decrypto(ms.ToArray(), "12345678");
                    string rs = Encoding.UTF8.GetString(DecryptoData);
                    Rs.Text = rs + "\r\n" + Rs.Text;
                }
            }
            if (rc == 8)
            {
                if (Cmd.Text.StartsWith("get"))
                {
                    filelength = BitConverter.ToInt64(ms.ToArray(), 0);
                    candown = true;
                    Rs.Text = "Request len = " + filelength + "\r\n" + Rs.Text;
                }
                else
                {
                    candown = false;
                }
            }

            if (!Cmd.Text.StartsWith("get"))
            {
                byte[] DecryptoData = DES.GetTransfer().Decrypto(ms.ToArray(), "12345678");
                string rs = Encoding.UTF8.GetString(DecryptoData);

                Rs.Text = rs + "\r\n" + Rs.Text;
            }
            else
            {
                if (candown)
                {
                    sock.Send(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 });
                    string fn = "temp.dat";
                    string[] tp = Cmd.Text.Split(' ');
                    if (tp.Length > 1)
                    {
                        fn = tp[1];
                    }
                    filename = fn;
                    cand = true;
                    backgroundWorker1.RunWorkerAsync();
                }
                else
                {
                    Rs.Text = "无法下载\r\n" + Rs.Text;
                }
            }
            Cmd.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int Port = 10898;
                if (!int.TryParse(lbPort.Text, out Port))
                {
                    Port = 10898;
                }

                sock.Connect(
                    new IPEndPoint(
                        IPAddress.Parse(lbIP.Text), Port
                        )
                    );
                Rs.Text = "Connect ok!\r\n" + Rs.Text;
                button1.Enabled = true;
            }
            catch (Exception ex)
            {
                Rs.Text = "Connect faild!" + ex.Message + "\r\n" + Rs.Text;
            }
            Rs.SelectionStart = Rs.TextLength;
        }

        private void SendCommand(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (handok)
                {
                    if (Cmd.Text.StartsWith("get"))
                    {
                        if (lbPath.Text != "N/A")
                        {
                            SendCommandData();
                        }
                        else
                        {
                            MessageBox.Show("请设定保存下载文件的目录");
                        }
                    }
                    else
                    {
                        SendCommandData();
                    }
                }
                Rs.SelectionStart = Rs.TextLength;
            }
           
        }

        private void StartDown(object sender, DoWorkEventArgs e)
        {
            if (cand)
            {
                
                try
                {
                    using (FileStream fs = new FileStream(lbPath.Text + "\\" + filename, FileMode.OpenOrCreate))
                    {
                        int kb = 0;
                        int rc = 0;
                        int i = 0;
                        byte[] bf = new byte[4096];
                        while ((rc = sock.Receive(bf)) > 0)
                        {
                            fs.Write(bf, 0, rc);
                            count += rc;
                            kb = (int)count / 1000;
                            backgroundWorker1.ReportProgress(kb);
                            i++;
                            if (count == filelength)
                            {
                                break;
                            }
                        }
                        fs.Flush();
                        fs.Close();
                    }
                }
                catch (Exception ex)
                {
                    Rs.Invoke(
                        (EventHandler)delegate(object sd, EventArgs args)
                    {
                        Rs.Text = ex.Message + "\r\n" + Rs.Text;  
                    });
                }
            }
        }

        private void SetCount(object sender, ProgressChangedEventArgs e)
        {
            lbcount.Text = e.ProgressPercentage.ToString();
        }

        private void workdone(object sender, RunWorkerCompletedEventArgs e)
        {
            cand = false;
            filelength = 0;
            count = 0;
            filename = string.Empty;
            Rs.Text = "File " + filename + " done\r\n" + Rs.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog(this);
            lbPath.Text = folderBrowserDialog1.SelectedPath;
        }
    }
}
